<template>
  <div class="file-management-container">
    <!-- 统计报表区域 -->
    <div class="chart-container">
      <div id="project-chart" class="chart-item"></div>
      <div id="type-chart" class="chart-item"></div>
    </div>

    <!-- 搜索表单 -->
    <div class="search-section">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="项目名称">
          <el-select
            v-model="searchForm.project"
            placeholder="请选择项目"
            clearable
            filterable
            class="search-input"
          >
            <el-option
              v-for="project in projects"
              :key="project"
              :label="project"
              :value="project"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="文件类型">
          <el-select
            v-model="searchForm.fileType"
            placeholder="请选择类型"
            clearable
            class="search-input"
          >
            <el-option label="PDF" value="PDF" />
            <el-option label="Word" value="Word" />
            <el-option label="Excel" value="Excel" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            class="search-input"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            <span>查询</span>
          </el-button>
          <el-button type="success" @click="uploadDialogVisible = true">
            <el-icon><Upload /></el-icon>
            <span>上传文件</span>
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <vxe-table
        border
        show-overflow
        highlight-hover-row
        :data="tableData"
        height="500"
        class="file-table"
      >
        <vxe-column type="seq" title="序号" width="60" align="center" />
        <vxe-column field="project" title="项目名称" min-width="120" />
        <vxe-column field="fileName" title="文件名称" min-width="180" />
        <vxe-column field="filePath" title="文件路径" min-width="250" />
        <vxe-column field="fileSize" title="文件大小" width="100" align="right" />
        <vxe-column field="fileType" title="文件类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="fileTypeTag(row.fileType)">
              {{ row.fileType }}
            </el-tag>
          </template>
        </vxe-column>
        <vxe-column field="remark" title="备注" min-width="150" />
        <vxe-column field="creator" title="创建人" width="100" />
        <vxe-column field="createTime" title="创建时间" width="160" />
        <vxe-column title="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="text">
              <el-icon><Download /></el-icon>
            </el-button>
            <el-button size="small" type="text" style="color: #ff4d4f">
              <el-icon><Delete /></el-icon>
            </el-button>
          </template>
        </vxe-column>
      </vxe-table>
    </div>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        background
      />
    </div>

    <!-- 文件上传弹框 -->
    <el-dialog
      title="文件上传"
      v-model="uploadDialogVisible"
      width="600px"
      @close="resetForm"
    >
      <el-form :model="uploadForm" ref="uploadForm" label-width="100px">
        <el-form-item label="项目名称" prop="projectName">
          <el-select
            v-model="uploadForm.projectName"
            placeholder="请选择项目"
            class="upload-select"
          >
            <el-option
              v-for="project in projects"
              :key="project"
              :label="project"
              :value="project"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="文件名称" prop="fileName">
          <el-input
            v-model="uploadForm.fileName"
            placeholder="请输入文件名称"
          />
        </el-form-item>

        <el-form-item label="文件路径" prop="filePath">
          <el-input
            v-model="uploadForm.filePath"
            placeholder="请输入文件路径"
          />
        </el-form-item>

        <el-form-item label="文件上传">
          <el-upload
            class="upload-area"
            drag
            action="/upload"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
            :file-list="fileList"
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">
              拖拽文件到这里，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持上传 PDF、Word 或 Excel 文件，单个文件不超过 10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUploadSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, onBeforeUnmount } from 'vue';
import { ElMessage, ElTag } from 'element-plus';
import { Search, Upload, Download, Delete, UploadFilled } from '@element-plus/icons-vue';
import * as echarts from 'echarts';

interface SearchForm {
  project: string;
  fileType: string;
  dateRange: string[];
}

interface UploadForm {
  projectName: string;
  fileName: string;
  filePath: string;
}

interface TableDataItem {
  project: string;
  fileName: string;
  filePath: string;
  fileSize: string;
  fileSizeNum: number;
  fileType: string;
  remark: string;
  creator: string;
  createTime: string;
}

export default defineComponent({
  components: { ElTag },
  setup() {
    const searchForm = ref<SearchForm>({
      project: '',
      fileType: '',
      dateRange: []
    });

    const tableData = ref<TableDataItem[]>([]);
    const fileList = ref<any[]>([]);
    const uploadDialogVisible = ref<boolean>(false);
    const uploadForm = ref<UploadForm>({
      projectName: '',
      fileName: '',
      filePath: '',
    });
    
    const projects = ['太化', '中天', '淮钢', '镔鑫', '东特', '三宝', '酒钢', '淮钢2期'];
    const projectChart = ref<echarts.ECharts | null>(null);
    const typeChart = ref<echarts.ECharts | null>(null);
    
    const currentPage = ref(1);
    const pageSize = ref(20);
    const total = ref(180);

    // 文件类型标签样式
    const fileTypeTag = (type: string) => {
      switch (type) {
        case 'PDF': return '';
        case 'Word': return 'success';
        case 'Excel': return 'warning';
        default: return 'info';
      }
    };

    // 生成假数据
    const generateFakeData = () => {
      const fakeData: TableDataItem[] = [];
      const totalEntries = 180;
      const numProjects = projects.length;
      const creators = ['张三', '李四', '王五', '赵六', '钱七', '孙八'];
      const fileTypes = ['PDF', 'Word', 'Excel'];
      
      // 生成数据
      for (let i = 0; i < totalEntries; i++) {
        const project = projects[i % numProjects];
        const fileType = fileTypes[Math.floor(Math.random() * fileTypes.length)];
        const fileSizeNum = Math.random() * 9.5 + 0.5; // 0.5-10MB
        const creator = creators[Math.floor(Math.random() * creators.length)];
        const date = new Date(Date.now() - Math.random() * 10000000000);
        const dateStr = `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
        
        fakeData.push({
          project: project,
          fileName: `文件_${i + 1}.${fileType.toLowerCase()}`,
          filePath: `/project/${project}/document_${i + 1}.${fileType.toLowerCase()}`,
          fileSize: `${fileSizeNum.toFixed(2)} MB`,
          fileSizeNum: fileSizeNum,
          fileType: fileType,
          remark: `备注信息_${i + 1}`,
          creator: creator,
          createTime: dateStr,
        });
      }

      tableData.value = fakeData;
      updateCharts();
    };

    // 初始化图表
    const initCharts = () => {
      const projectChartDom = document.getElementById('project-chart') as HTMLElement;
      const typeChartDom = document.getElementById('type-chart') as HTMLElement;
      
      projectChart.value = echarts.init(projectChartDom);
      typeChart.value = echarts.init(typeChartDom);
      
      updateCharts();
      
      // 响应窗口大小变化
      window.addEventListener('resize', () => {
        projectChart.value?.resize();
        typeChart.value?.resize();
      });
    };

    // 更新图表数据
    const updateCharts = () => {
      if (!projectChart.value || !typeChart.value) return;
      
      // 项目文件统计
      const projectCount: Record<string, number> = {};
      const projectSize: Record<string, number> = {};
      
      tableData.value.forEach(item => {
        projectCount[item.project] = (projectCount[item.project] || 0) + 1;
        projectSize[item.project] = (projectSize[item.project] || 0) + item.fileSizeNum;
      });
      
      // 文件类型统计
      const typeCount: Record<string, number> = {};
      tableData.value.forEach(item => {
        typeCount[item.fileType] = (typeCount[item.fileType] || 0) + 1;
      });
      
      // 项目图表配置
      projectChart.value.setOption({
        title: {
          text: '项目文件统计',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params: any) {
            return `${params[0].name}<br/>
                    文件数量: ${params[0].value}<br/>
                    文件大小: ${projectSize[params[0].name].toFixed(2)} MB`;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: Object.keys(projectCount),
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        yAxis: {
          type: 'value',
          name: '文件数量',
          nameTextStyle: {
            padding: [0, 30, 0, 0]
          }
        },
        series: [{
          name: '文件数量',
          type: 'bar',
          data: Object.values(projectCount),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 1, color: '#188df0' }
            ])
          },
          emphasis: {
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#2378f7' },
                { offset: 1, color: '#83bff6' }
              ])
            }
          }
        }]
      });
      
      // 文件类型图表配置
      const typeData = Object.entries(typeCount).map(([name, value]) => ({ 
        name, 
        value 
      }));
      
      typeChart.value.setOption({
        title: {
          text: '文件类型分布',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: Object.keys(typeCount)
        },
        series: [{
          name: '文件类型',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['40%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: typeData
        }]
      });
    };

    // 查询操作
    const handleSearch = () => {
      ElMessage.success('查询操作执行成功');
      generateFakeData();
    };

    // 文件上传成功后的处理
    const handleUploadSuccess = (response: any, file: any, fileListRef: any[]) => {
      fileList.value = fileListRef;
      ElMessage.success('文件上传成功！');
    };

    // 上传文件前的检查
    const beforeUpload = (file: File): boolean => {
      const isAllowed = [
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      ].includes(file.type);
      
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isAllowed) {
        ElMessage.error('只能上传 PDF、Word 或 Excel 文件！');
        return false;
      }
      
      if (!isLt10M) {
        ElMessage.error('文件大小不能超过 10MB！');
        return false;
      }
      
      return true;
    };

    // 提交文件上传信息
    const handleUploadSubmit = () => {
      if (!uploadForm.value.projectName) {
        ElMessage.warning('请选择项目名称');
        return;
      }
      
      if (!uploadForm.value.fileName) {
        ElMessage.warning('请输入文件名称');
        return;
      }
      
      uploadDialogVisible.value = false;
      resetForm();
      ElMessage.success('文件信息已上传');
    };

    // 重置表单
    const resetForm = () => {
      uploadForm.value.projectName = '';
      uploadForm.value.fileName = '';
      uploadForm.value.filePath = '';
      fileList.value = [];
    };

    onMounted(() => {
      generateFakeData();
      initCharts();
    });

    onBeforeUnmount(() => {
      if (projectChart.value) {
        projectChart.value.dispose();
      }
      if (typeChart.value) {
        typeChart.value.dispose();
      }
      window.removeEventListener('resize', () => {});
    });

    return {
      searchForm,
      tableData,
      fileList,
      uploadDialogVisible,
      uploadForm,
      projects,
      currentPage,
      pageSize,
      total,
      fileTypeTag,
      handleSearch,
      handleUploadSuccess,
      beforeUpload,
      handleUploadSubmit,
      resetForm,
    };
  },
});
</script>

<style scoped>
.file-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.chart-container {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-item {
  flex: 1;
  height: 300px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 10px;
}

.search-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.search-section .el-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 15px;
}

.search-input {
  width: 180px;
}

.table-container {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
}

.file-table {
  width: 100%;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  background: #fff;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.upload-select {
  width: 100%;
}

.upload-area {
  width: 100%;
}

.upload-area :deep(.el-upload) {
  width: 100%;
}

.upload-area :deep(.el-upload-dragger) {
  width: 100%;
  padding: 40px 20px;
}

.upload-area :deep(.el-icon) {
  font-size: 60px;
  color: #409eff;
  margin-bottom: 20px;
}
</style>